package com.ycb.coincap;

import org.java_websocket.client.WebSocketClient;
import org.java_websocket.enums.ReadyState;
import org.java_websocket.handshake.ServerHandshake;

import java.net.URI;
import java.time.LocalDateTime;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class WebSocketClientExample extends WebSocketClient {

    private final LocalDateTime startTime;
    private static int count = 1;

    public WebSocketClientExample(URI serverUri) {
        super(serverUri);
        startTime = LocalDateTime.now();
    }


    @Override
    public void onOpen(ServerHandshake handshakedata) {
        System.out.println("新连接已打开");
        // 发送消息给服务器
        send("1");
    }
 
    @Override
    public void onMessage(String message) {
        System.out.println( "["+LocalDateTime.now()+"]接收到消息 count:["+count+"] startTime: ["+startTime+"]: " + message);
    }
 
    @Override
    public void onClose(int code, String reason, boolean remote) {
        LocalDateTime endTime =  LocalDateTime.now();
        count++;
        System.out.println("["+LocalDateTime.now()+"]接收到消息 count:["+count+"] startTime: ["+endTime+"] 连接已关闭");
    }
 
    @Override
    public void onError(Exception ex) {
        ex.printStackTrace();
    }
 
    public static void main(String[] args) {
        try {
            WebSocketClientExample client = new WebSocketClientExample(new URI("wss://ws.coincap.io/prices?assets=ALL"));

            /**
             * 重连机制
             * 使用 ScheduledExecutorService   不要使用timer  timer不支持多线程,挂在timer下的任务都是单线程，如果任务运行时间过长影响其他任务运行
             *
             * ScheduledThreadPoolExecutor支持多线程。同一时候在线程中对异常进行了捕获。
             *
             * */
            ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(1);
            executorService.scheduleAtFixedRate(new Runnable() {
                @Override
                public void run() {
                    try{
                        if(client.getReadyState()!= ReadyState.OPEN) {
                            if(client.getReadyState()== ReadyState.NOT_YET_CONNECTED) {
                                if(client.isClosed()) {
                                    System.err.println("连接关闭,正在重新连接中……");
                                    client.reconnect();
                                }else{
                                    System.err.println("建立连接中……");
                                    client.connect();
                                }
                            }else if( client.getReadyState() == ReadyState.CLOSED){
                                System.err.println("连接关闭,正在重新连接中……");
                                client.reconnect();
                            }
                        }
                    }catch(Exception e) {
                        System.err.println("连接异常,正在重新连接中……");
                        client.reconnect();
                    }
                }
            },0,6000, TimeUnit.MILLISECONDS);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}